from django.http import HttpResponse

from api.paymethod import *
from rest_framework.views import APIView
from api.utils import * 
from api.models import *
from h5api.settings import IMAGE_DOMAIN_NAME,MALL_ALIPAY_CALLBACK_URI,XORPAY_CALLBACK_URI,ALIPAY_PUBLIC_KEY,ALIPAY_ADD_ID,ALIPAY_APP_PRIVATE_KEY
# Create your views here.

class GoodsAPI(APIView):


    #获取平台所有的商品信息
    def get(self,request,*args, **kwargs):
        goods = list(Goods.objects.all().values(
            "_id","goodsName","sellPrice","originPrice","stock","sellNumber","detail","image1","image2","image3","image4","image5"
        ))

        for goods_ in goods:
            goods_["image1"] = IMAGE_DOMAIN_NAME+str(goods_["image1"])
            goods_["image2"] = IMAGE_DOMAIN_NAME+str(goods_["image2"])
            goods_["image3"] = IMAGE_DOMAIN_NAME+str(goods_["image3"])
            goods_["image4"] = IMAGE_DOMAIN_NAME+str(goods_["image4"])
            goods_["image5"] = IMAGE_DOMAIN_NAME+str(goods_["image5"])

        return resultResponse(200,data=goods,_list=True)

class ConsumerAPI(APIView):

    #退出登录
    def get(self,request,*args, **kwargs):
        del request.session["consumer_id"]
        return resultResponse()

    #用户注册登录
    def post(self,request,*args, **kwargs):
        phone = request.data.get("phone",None)
        if not phone:
            return resultResponse(700,"无手机号")
        c = Consumer.objects.filter(phone=phone).first()
        if c:
            request.session["consumer_id"] = c._id 
            return resultResponse()
        consumer = dict()
        consumer["password"] = md5(request.data.get("password"))
        consumer["court"] = Court.objects.create()
        consumer = Consumer.objects.create(**consumer)
        request.session["consumer_id"] = consumer._id 
        return resultResponse()        

class CourtAPI(APIView):

    #获取购物车个人商品
    def get(self,request,*args, **kwargs):
        consumer_id = request.session.get("consumer_id")
        consumer = Consumer.objects.get(pk=consumer_id)
        court = consumer.court 
        goods_list = list(court.goods.all().values())
        for goods_ in goods_list:
            goods_["image1"] = IMAGE_DOMAIN_NAME+str(goods_["image1"])
            goods_["image2"] = IMAGE_DOMAIN_NAME+str(goods_["image2"])
            goods_["image3"] = IMAGE_DOMAIN_NAME+str(goods_["image3"])
            goods_["image4"] = IMAGE_DOMAIN_NAME+str(goods_["image4"])
            goods_["image5"] = IMAGE_DOMAIN_NAME+str(goods_["image5"])

        return resultResponse(data=goods_list,_list=True)

    #加入购物车
    def post(self,request,*args, **kwargs):
        goods_id = request.data.get("goodsId")
        consumer_id = request.session.get("consumer_id")
        goods = Goods.objects.get(pk=int(goods_id))
        consumer = Consumer.objects.get(pk=int(consumer_id))
        consumer.court.goods.add(goods) 
        return resultResponse()

    #移除购物车
    def delete(self,request,*args, **kwargs):
        goods_id = request.data.get("goodsId")
        consumer_id = request.session.get("consumer_id")
        goods = Goods.objects.get(pk=int(goods_id))
        consumer = Consumer.objects.get(pk=int(consumer_id))
        consumer.court.goods.remove(goods) 
        return resultResponse()

"""
清空购物车及购买商品
"""
class ClearCourtAPI(APIView):

    def put(self,request,*args, **kwargs):
        #用户地址填写支付商品 无需拦截  分销ID
        shop_id = request.data.get("shopId",None)
        if not shop_id:
            return resultResponse(700,"分销商ID")
        
        consumer_id = request.session.get("consumer_id")
        consumer = Consumer.objects.get(pk=int(consumer_id))

        #获取商品信息列表
        goods_list = consumer.court.goods.all()

        #查看是否有库存
        for goods in goods_list:
            if goods.stock <= 0:
                return resultResponse(700,goods.goodsName + "暂无库存")


        #获取收货地址
        address_id = int(request.data.get("addrId"))
        address = ShoppingAddress.objects.get(pk=address_id)

        #生成订单
        amount = 0.0 #总价钱
        goodsName = ""
        order_id_list = []
        for goods in goods_list:
            amount = amount + goods.sellPrice
            goodsName = goods.goodsName
            consumerOrder = dict()
            consumerOrder["orderNumber"] = createOrderId()
            consumerOrder["status"] = "未发货"
            consumerOrder["payStatus"] = "未支付"
            consumerOrder["consumer"] = consumer
            consumerOrder["distributionId"] = shop_id
            consumerOrder["shoppingAddress"] = address
            consumerOrder["goods"] = goods
            consumerOrder = ConsumerOrder.objects.create(**consumerOrder)
            order_id_list.append(consumerOrder._id)

            #跟新商品库存信息
            goods.stock = goods.stock - 1 
            goods.save()
        
        consumer_id_str = ','.join(str(x) for x in order_id_list)

        #根据需求生成支付链接
        paymethod = request.data.get("paymethod","支付宝")
        payLink = ""
        if paymethod == "支付宝":
            aliPay = AliPay.objects.filter(pk=1).first()
            if not aliPay:
                aliPay = AliPay.objects.create(appId=ALIPAY_ADD_ID,publicKey=ALIPAY_PUBLIC_KEY,privateKey=ALIPAY_APP_PRIVATE_KEY)
            payLink = getPayLinkAliPay(aliPay,{"sellPrice":amount,"goodsName":goodsName},consumer_id_str,MALL_ALIPAY_CALLBACK_URI)
        elif paymethod == "XorPay":
            payLink="https://mp.yxdlysxh.org.cn/static/goodsimages/alipayqr.png"
            # xorpay = XorPay.objects.get(pk=payId)
            # para = getPayLinkXorPay(xorpay,goods.sellData(),consumerOrder._id,XORPAY_CALLBACK_URI) 
            # if para["status"] == "ok":
            #     payLink = para['info']["qr"]
        else:
            pass 

        return resultResponse(data={"payLink":payLink,"paymethod":paymethod})

    def post(self,request,*args, **kwargs):
        #支付回调
        #goods.sellNumber = goods.sellNumber + 1#这个可以在支付成功后操作
        order_id_str = request.data.get("more",None)
        if order_id_str:#这个是xorpay 的
            order = ConsumerOrder.objects.get(pk=int(order_id))
            order.payStatus = "已支付"
            goods = order.goods 
            goods.sellNumber= goods.sellNumber + 1
            goods.save()
            order.save()
        else:
            out_trade_no = request.data.get("out_trade_no",None)#数据库中的_id  out_trade_no54
            trade_no = request.data.get("trade_no",None)#trade_no2022011622001492041409534372
            trade_status = request.data.get("trade_status",None)#trade_statusTRADE_SUCCESS
            order_id_list = out_trade_no.split(",")
            for order_id in order_id_list:
                order = ConsumerOrder.objects.get(pk=int(order_id))
                if trade_status == "TRADE_SUCCESS":
                    order.payStatus = "已支付"
                    order.tradeNo = trade_no
                    goods = order.goods 
                    goods.sellNumber= goods.sellNumber + 1
                    goods.save()
                    order.save()

        
        return HttpResponse("success")
    
class OrderInfoAPI(APIView):

    #获取我的订单
    def get(self,request,*args, **kwargs):
        consumer_id = request.session.get("consumer_id")
        order_list = list(ConsumerOrder.objects.filter(consumer_id = consumer_id,status__in=["未发货","下单","运送中"]).values("_id","goods__image2","goods__goodsName","goods__sellPrice","payStatus","status","expressName","expressNumber"))
        for item in order_list:
            item["goods__image2"] = IMAGE_DOMAIN_NAME+ item["goods__image2"]
        return resultResponse(200,data=order_list,_list = True )




class ShoppingAddressAPIView(APIView):
    
    #获取个人地址信息
    def get(self,request,*args, **kwargs):
        consumer_id = request.session.get("consumer_id")
        addr_list = list(ShoppingAddress.objects.filter(consumer_id=consumer_id,deleteStatus=False).values()) 
        return resultResponse(data=addr_list,_list=True)

    #添加个人地址信息
    def post(self,request,*args, **kwargs):
        consumer_id = request.session.get("consumer_id")
        address = getClassData(request,["address","addressDetail","name","phone"])
        address["consumer_id"] = consumer_id
        address = ShoppingAddress.objects.create(**address)
        return resultResponse()
   

    #删除个人地址信息
    def delete(self,request,*args, **kwargs):
        addr_id = int(request.data.get("addrId"))
        ShoppingAddress.objects.filter(_id=addr_id).update(deleteStatus=True)
        return resultResponse()


"""
售后服务
"""
class GoodsServiceAPIView(APIView):

    def __init__(self):
        super().__init__()
        self.CHECK_PACKAGE = "1"
        self.REFOUND = "2"
        self.CONFIRM_RECIVE = "3"

    def post(self,request,*args, **kwargs):
        _type = request.data.get("TYPE")
        orderId = request.data.get("orderId")
        if _type == self.CHECK_PACKAGE:
            co = ConsumerOrder.objects.get(pk=orderId)
            if not co.expressNumber:
                return resultResponse(700,"暂无物流信息")
            return resultResponse(200,{"express":co.expressName + ":"+co.expressNumber})
        elif _type == self.REFOUND:
            co = ConsumerOrder.objects.get(pk=orderId)
            if co.payStatus =="未支付":
                resultResponse(201,"未支付")
            co.payStatus = "申请退单"
            co.save()
            return resultResponse()
        elif _type == self.CONFIRM_RECIVE:
            co = ConsumerOrder.objects.get(pk=orderId)
            if co.payStatus =="未支付":
                resultResponse(201,"未支付")
            co.status = "已收货"
            co.save()
            return resultResponse()